from game.gui.widget import Widget


class Button(Widget):
    def __init__(self, **args):
        Widget.__init__(self, **args)

        self.state = 'idle'
        self.icons = {}
        args.setdefault("icon_idle",None)
        self.icons["idle"] = args["icon_idle"]
        args.setdefault("icon_hover",self.icons["idle"])
        self.icons["hover"] = args["icon_hover"]

        self.handlers = []
        self.action_perform = None

    #return value is 1 if the event is consumed, otherwise 0 if the event
    #should be passed on in the chain
    def receive(self, dat, evt):
        if evt.type == MOUSEBUTTONDOWN:
            pos_global = evt.pos
            pos_local = (pos_global[0] - self.rect[0], pos_global[1] - self.rect[1])
            if not self.rect.collidepoint(pos_local):
                return 0
            #The button is clicked, but not enabled, so consume but do nothing
            elif not self.enable:
                return 1
            else:
                self.clicked(evt)
                return 1

        if self.enable:
            if evt.type == MOUSEMOTION:
                pos_global = evt.pos
                pos_local = (pos_global[0] - self.rect[0], pos_global[1] - self.rect[1])
                if not self.rect.collidepoint(pos_local):
                    self.change_state('idle')
                elif state == 'idle':
                    self.change_state('hover')
                return 0

        return 0

    def clicked(self, evt):
        for h in self.handlers:
            h(evt)

    def change_state(self, state):
        self.state = state
        self.image = self.icons[state]
        self.make_dirty()


class RadialButton(Button):
    def __init__(self, **args):
        Button.__init__(self, **args)

        self.widget_type = 'radial_button'

    def receive(self, dat, evt):
        return 0


